<script>
export default {
  props: {
    value: {
      type: [Array, String],
      default: ''
    },
    type: {
      type: String,
      default: 'image'
    },
    limit: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      urlOrUrls: null,
      dialogVisible: false,
      previewObj: {}
    }
  },
  computed: {
    action() {
      const apiPath = {
        image: '/file/upload/upload?uploadItem=resPhotoLib',
        video: '/file/upload/uploadVideo?uploadItem=resPhotoLib'
      }[this.type]
      return this.cfg.apiDomain + apiPath
    },
    accept() {
      const res = {
        image: 'image/jpeg,image/gif,image/png,image/jpg,.svg,.svga',
        video: '.mp4'
      }[this.type]
      return res
    }
  },
  watch: {
    value: {
      handler(val) {
        if (typeof val === 'string') {
          this.urlOrUrls = val ? [val] : []
        }
        if (Array.isArray(val)) {
          this.urlOrUrls = val
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    change() {
      if (typeof this.value === 'string') {
        this.$emit('input', this.urlOrUrls.join(''))
      }
      if (Array.isArray(this.value)) {
        this.$emit('input', this.urlOrUrls)
      }
    },
    handlePictureCardPreview(e) {
      console.log(e);
      this.previewObj = e
      this.dialogVisible = true
    },
    handleRemove(e) {
      const index = this.urlOrUrls.findIndex(ele => ele === e.response.data.key)
      this.urlOrUrls.splice(index, 1)
      this.change()
    },
    onSuccess(e) {
      this.urlOrUrls.push(e.data.key)
      this.change()
    },
    handleClose(done) {
      this.previewObj = {}
      done()
    }
  }
}
</script>

<template>
  <div>
    <el-upload
      :action="action"
      :accept="accept"
      :list-type="{ image: 'picture-card', video: 'text' }[type]"
      :on-preview="handlePictureCardPreview"
      :on-success="onSuccess"
      :on-remove="handleRemove"
    >
      <i v-if="type === 'image'" class="el-icon-plus" />
      <el-button v-if="type === 'video'" icon="el-icon-plus" type="primary"> 选择视频 </el-button>
    </el-upload>
    <el-dialog
      title="预览"
      :visible.sync="dialogVisible"
      width="700px"
      :before-close="handleClose"
      :append-to-body="true"
    >
      <template v-if="previewObj.response && type === 'video'">
        <video muted autoplay :src="cfg.imageDomain + previewObj.response.data.key" style="width: 100%;" />
      </template>
      <template v-if="previewObj.response && type === 'image'">
        <img :src="cfg.imageDomain + previewObj.response.data.key" style="width: 100%;">
      </template>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>
